package com.example.demo.api;

import com.example.demo.entity.User;
import com.example.demo.entity.UserMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author CY
 * @date 2023/04/02 17:23
 **/
@RestController
@RequestMapping("/users")
public class UserApi {
    @Resource
    private UserMapper userMapper;

    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest request) {
        final User user = userMapper.selectByName(username);
        System.out.println("[login]:" + user.getUsername());
        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("登录失败失败");
            return new User();
        }
        final HttpSession session = request.getSession(true);
        if (session != null) {
            session.setAttribute("user", user);
        }
        user.setPassword("");
        return user;
    }


    @RequestMapping("/register")
    public Object register(String username, String password) {
        try {
            final User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insertUser(user);
            return user;
        } catch (Exception e) {
            return new User();
        }
    }

    @RequestMapping("/userInfo")
    public User getUser(String username, HttpServletRequest request) {
        try {
            final HttpSession session = request.getSession(false);
            final User user = (User) session.getAttribute("user");
            return user;
        } catch (Exception e) {
            return new User();
        }


    }

}
